""" 欢迎关注 "码农架构" 微信公众号，热爱开源，拥抱开源。一个IT民工的技术之路经验分享。
    - 问题咨询 / 建议
    1.关注微信公众号 "码农架构" 后私信
    2.可发送邮件: li.shangzhi@aliyun.com
"""
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/12/27 23:52
# @Author  : iByte

def modular_division(a, b, n):
    """
    >>> modular_division(4,8,5)
    2
    >>> modular_division(3,8,5)
    1
    >>> modular_division(4, 11, 5)
    4
    """
    assert n > 1 and a > 0 and greatest_common_divisor(a, n) == 1
    (d, t, s) = extended_gcd(n, a)
    x = (b * s) % n
    return x


def invert_modulo(a, n):
    """
    >>> invert_modulo(2, 5)
    3
    >>> invert_modulo(8,7)
    1
    """
    (b, x) = extended_euclid(a, n)
    if b < 0:
        b = (b % n + n) % n
    return b

def modular_division2(a, b, n):
    """
    >>> modular_division2(4,8,5)
    2
    >>> modular_division2(3,8,5)
    1
    >>> modular_division2(4, 11, 5)
    4
    """
    s = invert_modulo(a, n)
    x = (b * s) % n
    return x


def extended_gcd(a, b):
    """
    >>> extended_gcd(10, 6)
    (2, -1, 2)
    >>> extended_gcd(7, 5)
    (1, -2, 3)
    """
    assert a >= 0 and b >= 0

    if b == 0:
        d, x, y = a, 1, 0
    else:
        (d, p, q) = extended_gcd(b, a % b)
        x = q
        y = p - q * (a // b)

    assert a % d == 0 and b % d == 0
    assert d == a * x + b * y

    return (d, x, y)


def extended_euclid(a, b):
    """
    >>> extended_euclid(10, 6)
    (-1, 2)
    >>> extended_euclid(7, 5)
    (-2, 3)
    """
    if b == 0:
        return (1, 0)
    (x, y) = extended_euclid(b, a % b)
    k = a // b
    return (y, x - k * y)


# 欧几里得引理：d除a和b，当且仅当d除a-b和b
# 欧几里得算法

def greatest_common_divisor(a, b):
    """
    >>> greatest_common_divisor(7,5)
    >>> greatest_common_divisor(121, 11)
    11
    """
    if a < b:
        a, b = b, a

    while a % b != 0:
        a, b = b, a % b

    return b


from doctest import testmod

if __name__ == "__main__":
    testmod(name="modular_division", verbose=True)
    testmod(name="modular_division2", verbose=True)
    testmod(name="invert_modulo", verbose=True)
    testmod(name="extended_gcd", verbose=True)
    testmod(name="extended_euclid", verbose=True)
    testmod(name="greatest_common_divisor", verbose=True)